package com.tgy.leetcode;

import java.util.LinkedList;
import java.util.TreeSet;

/**
 * @Author: tgy
 * @Date: 2020-11-26 10:04
 *
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
public class _2_两数相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }

        if (l2 == null) {

            return l1;
        }

        ListNode headNode = new ListNode();
        ListNode tailNode = headNode;

        int carry = 0,bit = 0;
        int n1,n2;
        while (l1 != null || l2 != null) {

            n1 = l1 != null ? l1.val:0;
            n2 = l2 != null ? l2.val:0;

            int sum = n1 + n2 + carry;
            bit = sum % 10;
            carry = sum / 10;
            ListNode listNode = new ListNode(bit);
            tailNode.next = listNode;
            tailNode = listNode;

            if (l1 != null) {

                l1 = l1.next;
            }
            if (l2 != null) {

                l2 = l2.next;
            }
        }

        if (carry > 0) {

            tailNode.next = new ListNode(carry);
        }

        return headNode.next;
    }
}
